package com.dingchw.singlemusic.define.request;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dingchw.singlemusic.BootstrapApplication;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.Collection;

@RestControllerAdvice(basePackageClasses = {BootstrapApplication.class})
@Slf4j
public class RequestChecker implements RequestBodyAdvice {
    @Override
    public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {
        return new HttpInputMessage() {
            @Override
            public InputStream getBody() throws IOException {
                String bodyStr = IOUtils.toString(httpInputMessage.getBody(),"utf-8");
                Object obj = JSON.parse(bodyStr);
                if(obj instanceof JSONObject){
                    AbstractRequest abstractRequest = JSONObject.parseObject(bodyStr, AbstractRequest.class);
                    check(abstractRequest);
                }else{
                    Collection<AbstractRequest> abstractRequestList = JSON.parseArray(bodyStr, AbstractRequest.class);
                    check(abstractRequestList);
                }
                return httpInputMessage.getBody();
            }

            @Override
            public HttpHeaders getHeaders() {
                return httpInputMessage.getHeaders();
            }
        };
    }

    @Override
    public Object afterBodyRead(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        //check(o);
        return o;
    }

    @Override
    public Object handleEmptyBody(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return o;
    }

    private void check(Object o){
        if(o instanceof Collection){
            ((Collection) o).forEach(item->{
                if(item instanceof AbstractRequest){
                    ((AbstractRequest) item).check();
                }
            });
        }
    }
}
